//School of Informatics Xiamen University, GPL-3.0 license
package cn.edu.xmu.javaee.productdemomybatis.dao;

import cn.edu.xmu.javaee.core.exception.BusinessException;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.productdemomybatis.dao.bo.OnSale;
import cn.edu.xmu.javaee.productdemomybatis.mapper.generator.OnSalePoMapper;
import cn.edu.xmu.javaee.productdemomybatis.mapper.generator.po.OnSalePo;
import cn.edu.xmu.javaee.productdemomybatis.mapper.generator.po.OnSalePoExample;
import cn.edu.xmu.javaee.productdemomybatis.util.CloneFactory;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Repository
@Slf4j
@RequiredArgsConstructor
public class OnSaleDao {

    private final OnSalePoMapper onSalePoMapper;

    /**
     * 获得货品的最近的价格和库存
     * @param productId 货品对象
     * @return 规格对象
     */
    public List<OnSale> getLatestOnSale(Integer productId) throws DataAccessException {
        LocalDateTime now = LocalDateTime.now();
        List<OnSalePo> onsalePoList;
        try{
            OnSalePoExample example = new OnSalePoExample();
            example.setOrderByClause("end_time DESC");
            OnSalePoExample.Criteria criteria = example.createCriteria();
            criteria.andProductIdEqualTo(productId);
            criteria.andBeginTimeLessThanOrEqualTo(now);
            criteria.andEndTimeGreaterThanOrEqualTo(now);
            onsalePoList = onSalePoMapper.selectByExample(example);
        } catch (DataAccessException e) {
            log.error(e.getMessage());
            throw new BusinessException(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
        return onsalePoList.stream().map(po-> CloneFactory.copy(new OnSale(), po)).collect(Collectors.toList());
    }

    public void deleteByProductId(Integer productId) throws DataAccessException {
        try{
            OnSalePoExample example = new OnSalePoExample();
            example.createCriteria().andProductIdEqualTo(productId);
            this.onSalePoMapper.deleteByExample(example);
        } catch (DataAccessException e) {
            log.error(e.getMessage());
            throw new BusinessException(ReturnNo.INTERNAL_SERVER_ERR, e.getMessage());
        }
    }
}
